/*
   有5个工作线程, 分别循环向标准输出打印'a' 'b' 'c' 'd' 'e'
   要求整个进程执行10s, 输出结果abcdeabcde...
   main线程控制打印的顺序
 */
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <e_file.h>

#define THR_NR  5 
static int cur_id = -1;
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static void *thr_job (void *s);
int main (void)
{
	int i = 0;
	pthread_t tids[THR_NR] = {0};
	int err = 0;
	alarm (10);
	//创建工作线程
	for (i = 0; i < THR_NR; i++) {
		err = pthread_create (tids + i, NULL, thr_job,  (void *)i);
		if (err > 0) {
			fprintf (stderr, "pthread_create():%s\n", strerror(err));
			exit (1);
		}
	}
	//控制打印顺序 
	for (i = 0; ; i = (i+1) % THR_NR) {
		pthread_mutex_lock(&mut);
		while (cur_id != -1) {
			//上一个线程还没打印
			pthread_cond_wait (&cond, &mut);
		}
		cur_id = i;
		pthread_cond_broadcast (&cond);
		pthread_mutex_unlock (&mut);
	}

	for (i = 0; i < THR_NR; i++) {
		pthread_join (tids[i], NULL);
	}
	return 0;
}

static void *thr_job (void *s)
{
	int myid = (int)s;
	int c = 'a' + myid;

	while (1) {
		pthread_mutex_lock (&mut);
		while (myid != cur_id) {
			//不该打印
			pthread_cond_wait (&cond, &mut);
		}
		write (1, &c, 1);
		//cur_id == -1, 打印条件发生了
		cur_id = -1;
		pthread_cond_broadcast (&cond);
		pthread_mutex_unlock (&mut);
	}
	return NULL;
}

